import { forwardRef, useRef, useImperativeHandle, useEffect, useMemo } from 'react'
import { RenderForm } from '@inbiz/render';
import { getMessage } from '@inbiz/react';
import ControlTypeFormItem from './controlTypeFormItem';
import {
  ConditionItemType,
  defaultFileShowSchemaOptions,
  defaultFolderShowSchemaOptions,
} from '../../../../designer/conditionsSchema';
import { useInbiz } from '../../../../store/hooks/useInbiz';
import { useSearchUIState } from '../../../../store/hooks/useSearchUIState';
import { getDmsSearchData, getPageSearchData } from '../SmallPanelView/SmallPanelAdvancedSearch/utils'

import type { ForwardedRef } from 'react'
import type { InterfaceProps } from './controlTypeFormItem';
import type { SchemaOption } from '../../../../designer/conditionsSchema';
export type SelectLabelType = (
  | {
    type: 'local';
    data?: SchemaOption[];
  }
  | {
    type: 'remote';
    data?: object;
  }
) & { labelID?: string };
export type IFileFormItemRef = {
  reset: () => void;
  save: () => Promise<SelectLabelType> | undefined;
  search: () =>
    | Promise<{
      SearchWhere: string;
      rawSearchWhere: object;
      IndexName?: [string];
      inbiz?: ReturnType<typeof useInbiz>;
    }>
    | undefined;
};
interface FileFormItemProps {
  value?: SelectLabelType;
  onRemoveHandle?: (field: SchemaOption) => void;
  advancedSearchStyle?: 'style1' | 'style2';
  isDMS?: boolean;
  type?: string;
  searchEngineData: any,
  isFile?: boolean,
  isFolder?: boolean
}
// 文件
const FileFormItem = forwardRef(
  (props: FileFormItemProps, refs: ForwardedRef<IFileFormItemRef>) => {
    const inbiz = useInbiz();
    const ref = useRef<
      InterfaceProps & {
        page: typeof inbiz;
      }
    >();
    const { value, searchEngineData } = props;
    const { selectShowTab } = useSearchUIState();

    useImperativeHandle(
      refs,
      () => ({
        reset: () => {
          if (props.isDMS || props.isFile || props.isFolder) {
            ref.current?.reset?.();
          } else {
            ref.current?.page?.reset?.();
          }
        },
        save: () => {
          if (props.isDMS || props.isFile || props.isFolder) {
            return ref.current?.onSubmit?.().then((res) => {
              // setTimeout(() => {
              //   ref.current?.reset?.();
              // }, 0);
              if (
                Object.values(res)
                  .map((item) => item.value)
                  .some((item) => {
                    if (Array.isArray(item)) {
                      return !!item.length;
                    } else {
                      return item != undefined && item != null && item !== '';
                    }
                  })
              ) {
                const newLabel = Object.entries(res).reduce((dict, [, item]) => {
                  return [...dict, item];
                }, [] as ConditionItemType[]);
                return {
                  ...value,
                  data: newLabel.filter((item) => !!item),
                } as SelectLabelType;
              } else {
                return Promise.reject({
                  msg: getMessage('SearchEngine.pleaseEnterSearchCriteria'),
                });
              }
            });
          } else {
            const data = ref.current?.page?.getValue?.() || {};
            ref.current?.page?.reset?.();
            if (
              Object.values(data).some((item) => {
                if (Array.isArray(item)) {
                  return !!item.length;
                } else {
                  return item != undefined && item != null && item !== '';
                }
              })
            ) {
              return Promise.resolve({
                ...value,
                data,
              } as SelectLabelType);
            } else {
              return Promise.reject({
                msg: getMessage('SearchEngine.pleaseEnterSearchCriteria'),
              });
            }
          }
        },
        search: () => {
          if (props.isDMS || props.isFile || props.isFolder) {
            return ref.current?.onSubmit?.().then((res) => {
              let parentFolderLevel = null, parentFolderPath = '', parentTopFolderId = '', parentFolderid = ''
              if ((res.filepath && res.filepath.value) || (res.folderpath && res.folderpath.value)) {
                parentFolderLevel = res.filepath?.folderLevel || res.folderpath?.folderLevel
                parentFolderPath = res.filepath?.folderPath || res.folderpath?.folderPath
                parentTopFolderId = res.filepath?.topFolderId || res.folderpath?.topFolderId
                parentFolderid = res.filepath?.value?.[0].folderid || res.folderpath?.value?.[0].folderid
              }
              const newLabel = Object.entries(res).reduce((dict, [, item]) => {
                return [...dict, item];
              }, [] as ConditionItemType[]);
              return {
                SearchWhere: getDmsSearchData(newLabel),
                rawSearchWhere: newLabel,
                parentFolderLevel, 
                parentFolderPath, 
                parentTopFolderId, 
                parentFolderid
              };
            });
          } else {
            const $formTab = Object.values(
              (ref.current?.page.getSDK().form.fields || {}) as object,
            ).find((item: any) => item.data.componentType == 'FormTab')?.props?.name;
            const inbiz = ref.current?.page;
            if ($formTab) {
              const activeKey = inbiz?.($formTab).getActiveKey() as string;
              const rawSearchWhere = inbiz?.getValue(activeKey);
              return Promise.resolve({
                SearchWhere: getPageSearchData(rawSearchWhere),
                rawSearchWhere,
                IndexName: [activeKey],
                inbiz,
              });
            } else {
              const rawSearchWhere = ref.current?.page?.getValue?.() || {};
              return Promise.resolve({
                SearchWhere: getPageSearchData(rawSearchWhere),
                rawSearchWhere,
                inbiz,
              });
            }
          }
        },
      }),
      [value, props.isDMS],
    );
    const sdk = inbiz?.getGlobalSDK?.() || inbiz?.getSDK?.();
    const pageloading = useRef(false);
    useEffect(() => {
      if (!props.isDMS && pageloading.current && ref.current?.page?.setValues) {
        ref.current?.page?.reset();
        if (value?.data || Object.keys(value?.data! || {}).length !== 0) {
          ref.current?.page?.setValues(value?.data);
        }
      }
    }, [value]);
    const renderFormItem = useMemo(() => {
      // if (inbiz.browser.designer) {
      //   return null;
      // }
      if (!props.isDMS && selectShowTab?.associateAdvancedSearchPage) {
        const id = selectShowTab.associateAdvancedSearchPage.split(',')[0];
        // 渲染远程加载组件
        return (
          <RenderForm
            type="page"
            id={id}
            globalSDK={sdk}
            ref={ref}
            onInit={() => {
              pageloading.current = true;
            }}
          />
        );
      }
      if (props.isDMS) {
        return (
          <ControlTypeFormItem
            // @ts-ignore
            ref={ref}
            style={selectShowTab?.advancedSearchStyle || 'style2'}
            onRemoveHandle={props.onRemoveHandle!}
            fields={(value?.data as ConditionItemType[]) || []}
            searchEngineData={searchEngineData}
            defaultFields={
              props.type === 'file' ? defaultFileShowSchemaOptions : defaultFolderShowSchemaOptions
            }
          />
        );
      }
      return null;
    }, [value, sdk, props.isDMS, selectShowTab?.associateAdvancedSearchPage]);

    return <div className="render-form-wrapper">{renderFormItem}</div>;
  },
);

export default FileFormItem